import requests
import unittest
import json
from requests import sessions


class RequestsTests(unittest.TestCase):
    def __init__(self, methodName: str = ...):
        super().__init__(methodName)

    def setUp(self) -> None:
        self.getUrl = 'http://localhost:9909/python/demo/get'
        self.postUrl = 'http://localhost:9909/python/demo/post'
        self.putUrl = 'http://localhost:9909/python/demo/put'
        self.deleteUrl = 'http://localhost:9909/python/demo/delete'
        self.cookieUrl = 'http://localhost:9909/python/demo/cookie'

    # get
    def test_get(self):
        resp = requests.get(self.getUrl)
        text = resp.text
        print(json.loads(text))

    # post
    def test_post(self):
        postParams = {"name": "zs", "id": "123"}
        resp = requests.post(self.postUrl, json=postParams)
        print(json.loads(resp.text))

    # put
    def test_put(self):
        putParams = {"name": "zs", "id": "123"}
        resp = requests.put(self.putUrl, json=putParams)
        print(json.loads(resp.text))

    # delete
    def test_delete(self):
        deleteParams = {"name": "zs", "id": "123"}
        resp = requests.delete(self.deleteUrl, json=deleteParams)
        print(json.loads(resp.text))

    # cookie
    def test_cookie(self):
        resp = requests.get(self.cookieUrl)
        cookies = resp.cookies
        for key in cookies.keys():
            print("key:[%s]--value:[%s]" % (key, resp.cookies.get(key)))
        print(json.loads(resp.text))
        print("-------携带cookie---------")
        resp2 = requests.get(self.getUrl, cookies=cookies)
        print(json.loads(resp2.text))

    # session
    def test_session(self):
        session = sessions.Session()
        response = session.get("https://www.baidu.com/s?wd=python")
        # or
        # requests = sessions.Session()
        # response = requests.get("https://www.baidu.com/s", params={"wd": "python"})

        print(u"请求的URL: ", response.request.url)
        print(u"请求的参数(GET方法专属): ", response.request.path_url)
        print(u"请求的Method: ", response.request.method)
        print(u"请求的头: ", response.request.headers)

        print(u"响应状态码: ", response.status_code)
        print(u"响应头: ", response.headers)
        print(u"响应内容: ", response.content)

        print(u"请求所带的cookie和响应所返回的cookie集合: ", response.cookies)
        print(u"总共耗时: ", response.elapsed)


if __name__ == '__main__':
    unittest.main(verbosity=2)
